package com.emath.activities;

import java.text.DecimalFormat;
import org.json.JSONException;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.graphics.Typeface;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Debug;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.TranslateAnimation;
import android.widget.TextView;
import android.widget.Toast;

import com.emath.ConnecttoPlayer;
import com.emath.HelpDialog;
import com.lnl.R;
import com.emath.objects.Game;
import com.emath.objects.OpponentPlayer;
import com.emath.objects.Player;
import com.emath.objects.Username;
import com.emath.shared.Globals;
import com.emath.shared.RestClient;

public class GameMenu extends Activity {
	public static final String PREFS_NAME = "sampleGameSettings";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		logHeap();
		getWindow().setFormat(PixelFormat.RGBA_8888);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_DITHER);
		setContentView(R.layout.activity_main);
		final MediaPlayer buttonsound = MediaPlayer.create(GameMenu.this,
				R.raw.button_click);

		// Translation
		Animation trans = new TranslateAnimation(-400, 0, 0, 0);
		trans.setDuration(3000); // 3 Seconds
		AnimationSet animSet = new AnimationSet(true);
		animSet.setFillEnabled(true);
		animSet.addAnimation(trans);

		Typeface capture = Typeface.createFromAsset(getAssets(),
				"fonts/Capture_it.ttf");

		TextView myidTitle = (TextView) findViewById(R.id.idTitle);
		myidTitle.setTypeface(capture);
		TextView myid = (TextView) findViewById(R.id.myid);
		myid.setText(Username.getUser());
		TextView skillTitle = (TextView) findViewById(R.id.skillTitle);
		skillTitle.setTypeface(capture);
		TextView skill = (TextView) findViewById(R.id.skill);
		skill.setText("" + Globals.user.getSkillLevel());
		TextView findGameBtn = (TextView) findViewById(R.id.findGame);
		TextView createGameBtn = (TextView) findViewById(R.id.createGame);
		TextView collectionMgrBtn = (TextView) findViewById(R.id.collectionMgr);
		TextView cardShopBtn = (TextView) findViewById(R.id.cardShop);
		TextView settingsBtn = (TextView) findViewById(R.id.settings);
		TextView exitBtn = (TextView) findViewById(R.id.exitGame);

		findGameBtn.setTypeface(capture);
		createGameBtn.setTypeface(capture);
		collectionMgrBtn.setTypeface(capture);
		cardShopBtn.setTypeface(capture);
		settingsBtn.setTypeface(capture);
		exitBtn.setTypeface(capture);

		findGameBtn.startAnimation(animSet);
		createGameBtn.startAnimation(animSet);
		collectionMgrBtn.startAnimation(animSet);
		cardShopBtn.startAnimation(animSet);
		settingsBtn.startAnimation(animSet);
		exitBtn.startAnimation(animSet);

		findGameBtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				buttonsound.start();
				new Connecting().execute(getApplicationContext());
			}
		});
		createGameBtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				buttonsound.start();
				Intent intent = new Intent(getApplicationContext(),
						ConnecttoPlayer.class);
				Globals.focusedActivity = "ConnecttoPlayer";
				startActivity(intent);
			}
		});
		collectionMgrBtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				buttonsound.start();
				new Collection().execute(getApplicationContext());
			}
		});
		cardShopBtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				buttonsound.start();
				new Library().execute(getApplicationContext());
			}
		});
		settingsBtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				buttonsound.start();
				Globals.focusedActivity = "SettingsActivity";
				startActivity(new Intent("com.emath.SETTING"));
			}
		});
		exitBtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				RestClient Connect = new RestClient();
				
							
				buttonsound.start();
				String logout = "http://emath-project.appspot.com/emath/emathservicehttp?function=logout&userID="
						+ Username.getUser();
				Connect.connect(logout);
				if (Globals.isconnected== 0){
					Toast.makeText(GameMenu.this, "Connection Error", Toast.LENGTH_LONG).show();
					Globals.isconnected=1;
				}
				else{
				Connect.clear();
				finish();
				Intent intent = new Intent(Intent.ACTION_MAIN);
				intent.addCategory(Intent.CATEGORY_HOME);
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				Globals.focusedActivity = "NA";
				startActivity(intent);

				int pid = android.os.Process.myPid();
				android.os.Process.killProcess(pid);
				}
				
			}
		});

	}

	public class Collection extends AsyncTask<Context, Void, Context> {
		ProgressDialog dialog;

		@Override
		protected Context doInBackground(Context... Contexts) {
			while (!Globals.collectionObj.getObjectState().equals("free")) {
				try {// to get cards in collection
					if (Globals.collectionObj.getObjectState().equals(""))
						Globals.collectionObj.sqlGetCollection();
					Thread.sleep(50);
				} catch (InterruptedException e) {
					e.printStackTrace();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			Globals.focusedActivity = "CollectionMgr";
			startActivity(new Intent("com.emath.COLLECTIONMGR"));
			return Contexts[0];
		}

		protected void onPreExecute() {
			dialog = ProgressDialog.show(GameMenu.this, "",
					"Loading your collection.", true);
		}
		@Override
		protected void onPostExecute(Context result) {
			dialog.dismiss();
			super.onPostExecute(result);
		}
	}

	public class Library extends AsyncTask<Context, Void, Context> {
		ProgressDialog dialog;

		@Override
		protected Context doInBackground(Context... Contexts) {
			while (!Globals.user.getObjectState().equals("free")) {
				try { // to get tokens
					if (Globals.user.getObjectState().equals(""))
						Globals.user.sqlGetUser();
					Thread.sleep(50);
				} catch (InterruptedException e) {
					e.printStackTrace();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			while (!Globals.libraryObj.getObjectState().equals("free")) {
				try { // to get cards in library
					if (Globals.libraryObj.getObjectState().equals(""))
						Globals.libraryObj.sqlGetLibrary();
					Thread.sleep(50);
				} catch (InterruptedException e) {
					e.printStackTrace();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			while (!Globals.collectionObj.getObjectState().equals("free")) {
				try { // to get cards in collection
					if (Globals.collectionObj.getObjectState().equals(""))
						Globals.collectionObj.sqlGetCollection();
					Thread.sleep(50);
				} catch (InterruptedException e) {
					e.printStackTrace();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			Globals.focusedActivity = "CardShop";
			startActivity(new Intent("com.emath.CARDSHOP"));
			return Contexts[0];
		}
		protected void onPreExecute() {
			dialog = ProgressDialog.show(GameMenu.this, "",
					"Loading the card library.", true);
		}
		@Override
		protected void onPostExecute(Context result) {
			dialog.dismiss();
			super.onPostExecute(result);
		}
	}

	public class Connecting extends AsyncTask<Context, Void, Context> {
		ProgressDialog dialog;
		RestClient Connect = new RestClient(GameMenu.this);
		protected Context doInBackground(Context... Contexts) {

			String findgame = "http://emath-project.appspot.com/emath/emathservicehttp?function=findgame&userID="
					+ Username.getUser();
			Connect.connect(findgame);

			return Contexts[0];
		}

		protected void onPreExecute() {
			dialog = ProgressDialog.show(GameMenu.this, "", "Finding", true);

		}

		protected void onPostExecute(Context result) {

			int index = Connect.findindex("round");
			try {
				if (index != -1
						&& Connect.getvalArray().getString(index)
								.equals("waiting")) {
					String id = null;
					index = Connect.findindex("gameID");
					try {
						id = Connect.getvalArray().getString(index);
					} catch (JSONException e) {
						e.printStackTrace();
					}
					Game.setGameID(id);

					Connect.clear();
					Player.setPlayer("p2");
					OpponentPlayer.setPlayer("p1");
					Game.setCreatedgame(false);
					dialog.dismiss();

					Intent f = new Intent(getApplicationContext(),
							GamePlay.class);
					Globals.focusedActivity = "GamePlay";
					startActivity(f);

				} else {
					Connect.clear();
					dialog.dismiss();
					AlertDialog.Builder builder = new AlertDialog.Builder(
							GameMenu.this);
					builder.setMessage("Can't Find Game").setNegativeButton(
							"Cancel", new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									// User cancelled the dialog
								}
							});
					// Create the AlertDialog object and return it
					builder.create();
					builder.show();
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public void onBackPressed() {
	}

	@Override
	protected void onPause() {
		if (Globals.focusedActivity.equals("GameMenu")) {
			if (Globals.isMusicPlaying) {
				if (Globals.settingsHolder[1] == 1) {
					stopService(Globals.backgroundMusicService);
				}
				Globals.isMusicPlaying = false;
			}
		}
		super.onPause();
	}

	
	
	@Override
	protected void onResume() {
		if (!Globals.isMusicPlaying) {
			if (Globals.settingsHolder[1] == 1) {
				startService(Globals.backgroundMusicService);
			}
			Globals.isMusicPlaying = true;
		}
		super.onResume();
	}

	public void displayhelp() {

		HelpDialog helpDialog = new HelpDialog(GameMenu.this);
		helpDialog.setTitle("Help contents");
		helpDialog.show();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.ingamemenu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		switch (item.getItemId()) {
		case R.id.exit:
			RestClient Connect = new RestClient(GameMenu.this);
			final MediaPlayer buttonsound = MediaPlayer.create(GameMenu.this,
					R.raw.button_click);
			buttonsound.start();
			String logout = "http://emath-project.appspot.com/emath/emathservicehttp?function=logout&userID="
					+ Username.getUser();
			Connect.connect(logout);
			Connect.clear();
			stopService(Globals.backgroundMusicService);
			Globals.isMusicPlaying = false;
			finish();
			return true;
		case R.id.help:
			displayhelp();
			return true;
		}
		return super.onOptionsItemSelected(item);

	}
	public static void logHeap() {
		Double allocated = new Double(Debug.getNativeHeapAllocatedSize())
				/ new Double((1048576));
		Double available = new Double(Debug.getNativeHeapSize()) / 1048576.0;
		Double free = new Double(Debug.getNativeHeapFreeSize()) / 1048576.0;
		DecimalFormat df = new DecimalFormat();
		df.setMaximumFractionDigits(2);
		df.setMinimumFractionDigits(2);
		Runtime rt = Runtime.getRuntime();
		long maxMemory = rt.maxMemory();
		Log.v("memory3", "maxMemory:" + Long.toString(maxMemory));
		Log.e("memory3", "debug. =================================");
		Log.e("memory3", "debug.heap native: allocated " + df.format(allocated)
				+ "MB of " + df.format(available) + "MB (" + df.format(free)
				+ "MB free)");
		Log.e("memory3",
				"debug.memory: allocated: "
						+ df.format(new Double(Runtime.getRuntime()
								.totalMemory() / 1048576))
						+ "MB of "
						+ df.format(new Double(
								Runtime.getRuntime().maxMemory() / 1048576))
						+ "MB ("
						+ df.format(new Double(Runtime.getRuntime()
								.freeMemory() / 1048576)) + "MB free)");
	}

	@Override
	protected void onStart() {
		super.onStart();
		logHeap();
		if (Username.getUser() == null)
			finish();

	}

}
